#pragma once
#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <vector>

using namespace std;
string galbalhost = "47.109.203.137";
string galbaluser = "zgw";
string galabalpassword = "202408lbwnB.";
string galbaldb = "chat";
int _gport = 3306;

class Mysqlconnect
{
public:
    Mysqlconnect()
        : _host(galbalhost), _user(galbaluser), _password(galabalpassword), _db(galbaldb), _mysql(nullptr)
    {
        _mysql = mysql_init(nullptr);
    }
    void Connect()
    {
        if ( mysql_real_connect(_mysql, _host.c_str(), _user.c_str(), _password.c_str(), _db.c_str(), _gport, nullptr, 0) == nullptr)
        {
            cout << "连接失败" << endl;
            return;
        }
        mysql_set_character_set(_mysql, "utf-8");
    }
    bool LoadData(vector<string >&data)
    {
        string sql = "select jsdata from chat_data;";
        mysql_query(_mysql, sql.c_str());
        MYSQL_RES *res = mysql_store_result(_mysql);
        if (res == nullptr)
        {
            cout << "查询失败" << endl;
            return false;
        }
        cout << "查询结果如下:" << endl;
        int row = mysql_num_rows(res);               // 获取结果集的行数
        int col = mysql_num_fields(res);             // 获取结果集的列数
        MYSQL_FIELD *field = mysql_fetch_field(res); // 获取结果集的列信息
        for (int i = 0; i < row; i++)
        {
            MYSQL_ROW row = mysql_fetch_row(res); // 获取结果集的每一行数据
            for (int j = 0; j < col; j++)
            {
                cout << row[j] << " ";
                data.push_back(row[j]);
            }
            cout << endl;
        }
        return true;
    }
    void InsertData(string data)
    {
        string sql = "insert into chat_data(jsdata) values('"+data+"');";
        mysql_query(_mysql, sql.c_str());
        if (mysql_affected_rows(_mysql) == 1)
        {
            cout << "插入成功" << endl;
        }
    }
    ~Mysqlconnect()
    {
    }

private:
    string _host;
    string _user;
    string _password;
    string _db;
    MYSQL *_mysql;
};
